package com.zwk.sms.controller;

import com.zwk.base.entity.CommonResult;
import com.zwk.base.util.JwtUtils;
import com.zwk.base.util.RandomUtil;
import com.zwk.sms.service.SmsService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @author zwk
 * @create 2022/8/28 14:59
 */
@RestController
@CrossOrigin
@RequestMapping("/sms")
public class SmsController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    // 发送短信(阿里云短信测试)
    @GetMapping("/send/{phone}")
    public CommonResult sendSms(@PathVariable("phone") String phone){
        phone = "15294624205"; // 阿里云短信测试, 要用绑定的手机号
        // 先从redis中取，没有再发送
        String redisCode = redisTemplate.opsForValue().get(phone);
        if (ObjectUtils.isNotEmpty(redisCode)){
            return CommonResult.ok();
        }
        String code = RandomUtil.getFourBitRandom();
        boolean result = smsService.send(phone, code);

        if (result){
            // 设置有效时间
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return CommonResult.ok();
        }
        return CommonResult.error().message("短信发送失败");
    }


}
